package com.tianzhu.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.webflow.config.AbstractFlowConfiguration;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.ViewFactoryCreator;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.executor.FlowExecutor;
import org.springframework.webflow.mvc.builder.MvcViewFactoryCreator;
import org.springframework.webflow.mvc.servlet.FlowHandlerAdapter;
import org.springframework.webflow.mvc.servlet.FlowHandlerMapping;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

@Configuration
public class WebFlowConfig extends AbstractFlowConfiguration {

	@Autowired
	private ThymeleafViewResolver viewResolver;
	
		
	@Bean
	public FlowExecutor flowExecutor() {
	    return getFlowExecutorBuilder(flowRegistry()).build();
	}
	
	
	@Bean
	public FlowDefinitionRegistry flowRegistry() {
		return getFlowDefinitionRegistryBuilder(flowBuilderServices())
				.setBasePath("classpath:flows")
		        .addFlowLocationPattern("/**/*-flow.xml")
	            //.addFlowLocation("/checkout/checkout-flow.xml","checkout")
	            .build();
	}
	
	@Bean
	public FlowHandlerMapping flowHandlerMapping(){
		
		FlowHandlerMapping flowHandlerMapping = new FlowHandlerMapping();
		
		flowHandlerMapping.setFlowRegistry(flowRegistry());
		return flowHandlerMapping;
	}
	
	
	
	@Bean
	public FlowHandlerAdapter flowHandlerAdapter(){
		
		FlowHandlerAdapter flowHandlerAdapter = new FlowHandlerAdapter();
		
		flowHandlerAdapter.setFlowExecutor(flowExecutor());
		return flowHandlerAdapter;
	}
	
	@Bean
	public FlowBuilderServices flowBuilderServices() {
	    return getFlowBuilderServicesBuilder()
	    		.setViewFactoryCreator(viewFactoryCreator())
	    		.build();
	}
	
	@Bean
	public ViewFactoryCreator viewFactoryCreator() {
		
		MvcViewFactoryCreator mvcViewFactoryCreator = new MvcViewFactoryCreator();
		List<ViewResolver> list=new ArrayList();
		list.add(viewResolver);
		mvcViewFactoryCreator.setViewResolvers((list));
	   return mvcViewFactoryCreator;
	}
	
}
